<template>
  <div class="institutions-jobs-area-page">
    <div class="left">
      <el-card class="card">
        <el-tree
          class="tree"
          :data="treeList"
          :props="treeDefaultProps"
          node-key="id"
          :expand-on-click-node="false"
          :current-node-key="currentNodeKey"
          :default-expanded-keys="[currentNodeKey]"
          highlight-current
          @current-change="handleSelectTreeNode"
        >
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <!-- 没有子节点，也就是叶子节点 -->
            <svg-icon v-if="!data.children" style="margin-right: 0px;" icon-class="" class="tree-icon svgIcon" />
            <!-- 展开 -->
            <svg-icon v-else-if="node.expanded" icon-class="floder-open" class=" tree-icon svgIcon" />
            <!-- 关闭 -->
            <svg-icon v-else icon-class="floder-close" class="tree-icon svgIcon" />
            <!-- 节点文字 -->
            <span class="tree-icon-text" :title="node.label">{{ node.label }}</span>
          </span>
        </el-tree>
      </el-card>
    </div>

    <div class="right">
      <el-card class="card">
        <div slot="header" class="clearfix">
          <el-row type="flex" justify="space-between" align="center">
            <span style="line-height: 36px">作业范围</span>
            <div>
              <el-button
                v-if="isEditMode"
                size="medium"
                type="primary"
                @click="submit"
              >提交</el-button>
              <el-button
                v-if="isEditMode"
                size="medium"
                plain
                @click="cancel"
              >取消</el-button>
              <el-button
                v-else
                size="medium"
                type="primary"
                @click="edit"
              >编辑</el-button>
            </div>
          </el-row>
        </div>

        <el-row class="search-box" type="flex" justify="start" align="middle">
          <span>地区关键词：</span>
          <el-input
            v-model="queryParams.keyword"
            style="width: 230px"
            placeholder="请输入地区关键词"
          />
        </el-row>
        <div class="map-container">
          <div v-if="isEditMode" class="option-bar">
            <el-row type="flex" justify="start" align="middle">
              <el-button type="danger" plain @click="toggleDrawing">{{
                mapData.isDrawing ? "完成绘制" : "开始绘制"
              }}</el-button>
              <el-button
                v-if="mapData.isDrawing"
                plain
                @click="deleteInstitutionsJobsArea"
              >删除围栏</el-button>
            </el-row>
            <div class="tip-bar">
              <i class="tip-icon el-icon-info" />
              <span
                class="tip"
              >点击或拖动鼠标绘制作业范围，右击鼠标结束图形绘制，图形不可有交叉点。完成绘制后，点击提交按钮保存。每个机构仅可支持绘制一个作业范围</span>
            </div>
          </div>

          <!-- :scroll-wheel-zoom="true"，滚轮缩放 -->
          <!-- @click="startNewPolyline"，鼠标左键点击事件 -->
          <!-- @rightclick="addPolyline"，鼠标右键点击事件 -->
          <!-- @mousemove="syncPolyline"，鼠标移动事件 -->
          <baidu-map
            :center="mapData.center"
            :zoom="mapData.zoom"
            :scroll-wheel-zoom="true"
            class="bm-view"
            @click="startNewPolyline"
            @rightclick="addPolyline"
            @ready="onMapReady"
          >
            <!--
                多边形
                  path：构成折线的点
                  stroke-color：折线颜色
                  stroke-opacity：折线的透明度，取值范围0 - 1
                  stroke-style：折线的样式，solid或dashed
                  stroke-weight：折线的宽度，以像素为单位
                  editing：是否可以编辑
                  fill-color：填充颜色。当参数为空时，折线覆盖物将没有填充效果
                  fill-opacity：填充的透明度，取值范围0 - 1
             -->
            <bm-polygon
              :path="mapData.polygonPath"
              stroke-color="red"
              :stroke-opacity="0.5"
              stroke-style="solid"
              :stroke-weight="2"
              :editing="mapData.isDrawing"
              :fill-color="mapData.fillColor"
              :fill-opacity="0.3"
              @lineupdate="updatePolygonPath"
            />

            <bm-local-search
              :keyword="queryParams.keyword"
              :page-capacity="3"
              class="map-location"
              :panel="true"
              :auto-viewport="true"
              @infohtmlset="searchComplete"
            />
          </baidu-map>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getOrganizationTreeList } from '@/api/organization'
import {
  getInstitutionsJobsArea,
  saveInstitutionsJobsArea,
  deleteInstitutionsJobsArea
} from '@/api/institutions-jobs-area'
import { getTreeNodeFirstLeafNode } from '@/utils/index'
/**
 * 位置搜索
 */
import BmLocalSearch from 'vue-baidu-map/components/search/LocalSearch.vue'

export default {
  name: 'OrganizationManagePage',
  components: {
    BmLocalSearch
  },
  data() {
    return {
      // 是否是编辑模式
      isEditMode: false,
      // 机构树形数据
      treeList: [],
      // 员工列表
      list: [],
      // 树形结构的字段映射配置
      treeDefaultProps: {
        label: 'name',
        children: 'children'
      },
      // 查询参数
      queryParams: {
        // 业务Id，这里是机构Id
        bid: '',
        // 类型，1-机构，2-快递员
        type: 1,
        // 搜索关键字
        keyword: ''
      },
      // 地图数据
      mapData: {
        // 地图中心点（经纬度坐标）
        center: {
          lng: 0,
          lat: 0
        },
        // 多边形数组
        polygonPath: [],
        // 缩放层级
        zoom: 15,
        // 填充颜色
        fillColor: '#FF0000',
        // 是否开始绘制了
        isDrawing: false
      },
      // 当前选择的节点的Id
      currentNodeKey: '1024985257948084801'
    }
  },
  created() {
    this.getOrganizationTreeList()
  },
  methods: {
    // 获取结构树形列表
    async getOrganizationTreeList() {
      const result = await getOrganizationTreeList()
      console.log(result)

      // 解析返回的树形数据为数组
      const dataJson = result.data
      // 更新机构树形数据
      this.treeList = JSON.parse(dataJson)

      const firstLeafNode = getTreeNodeFirstLeafNode(this.treeList[0])
      console.log('第一个叶子节点：', firstLeafNode)

      // 获取第一个机构，并默认选中它
      this.queryParams.bid = firstLeafNode.id
      // 设置树形组件，当前选中的id
      this.currentNodeKey = this.queryParams.bid
      console.log(`进入页面，默认选中的机构Id => ${this.currentNodeKey}`)

      // 切换机构，那么同步作业范围
      this.getOrganizationInstitutionsJobsArea()
    },
    // 获取机构的作业范围
    async getOrganizationInstitutionsJobsArea() {
      const result = await getInstitutionsJobsArea(
        this.queryParams.bid,
        this.queryParams.type
      )
      console.log(result)

      const mapResource = result.data

      // 更新地图的经度、纬度
      this.mapData.center = {
        lng: mapResource.longitude,
        lat: mapResource.latitude
      }

      // 回显多边形
      const polygonList = mapResource.polygon || []
      this.mapData.polygonPath = polygonList.map((item) => {
        return {
          lng: item.longitude,
          lat: item.latitude
        }
      })
    },
    // 处理选中的树形节点改变
    handleSelectTreeNode(node) {
      console.log(node)
      // 更新当前选中的节点id
      this.queryParams.bid = node.id

      // 切换机构，那么同步作业范围
      this.getOrganizationInstitutionsJobsArea()
    },
    // 地图初始化完毕
    onMapReady({ BMap, map }) {
      // console.log(BMap, map)
      console.log('百度地图 => 初始化完毕...')
      // 设置初始中心点的经纬度
      this.mapData.center.lng = 116.404
      this.mapData.center.lat = 39.915
      // 缩放等级
      this.mapData.zoom = 10
    },
    // 切换开始绘制和完成绘制
    async toggleDrawing() {
      this.mapData.isDrawing = !this.mapData.isDrawing
    },
    // 删除作业范围
    async deleteInstitutionsJobsArea() {
      try {
        const result = await deleteInstitutionsJobsArea(
          this.queryParams.bid,
          this.queryParams.type
        )
        console.log(result)
        console.log('删除作业范围 => 成功')
        this.$message.success('删除成功')
        // 重新拉取作业范围数据
        this.getOrganizationInstitutionsJobsArea()
        // 结束绘制
        this.mapData.isDrawing = false
      } catch (e) {
        console.log('删除作业范围 => 失败', e)
      }
    },
    // POI搜索完毕
    searchComplete() {
      console.log('POI搜索完毕...')
    },
    // 更新多边形
    updatePolygonPath(e) {
      console.log('更新多边形...')
      this.mapData.polygonPath = e.target.getPath()
    },
    // 编辑
    edit() {
      this.isEditMode = !this.isEditMode
    },
    // 鼠标左键，开始一个新的多边形
    startNewPolyline(e) {
      // 没有开始绘制，不处理
      if (!this.mapData.isDrawing) {
        return
      }

      // 添加点击坐标到数组中
      this.mapData.polygonPath.push({
        lng: e.point.lng,
        lat: e.point.lat
      })
    },
    // 鼠标移动，同步连线
    syncPolyline(e) {
      // 没有开始绘制，不处理
      if (!this.mapData.isDrawing) {
        return
      }

      const polygonPath = this.mapData.polygonPath

      // 如果没有设置过第一个坐标点，则忽略
      let pointObj = polygonPath[polygonPath.length - 1]
      if (!pointObj) {
        return
      }

      // console.log(`更新前坐标：[${pointObj.lng},${pointObj.lat}]`)
      pointObj = {
        lng: e.point.lng,
        lat: e.point.lat
      }
      // console.log(`更新后坐标：[${pointObj.lng},${pointObj.lat}]`)

      // 通知Vue更新视图
      this.$set(this.mapData, 'polygonPath', polygonPath)
    },
    // 右键，结束绘制
    addPolyline(e) {
      this.mapData.isDrawing = false
    },
    // 提交
    async submit() {
      try {
        // 结束绘制
        this.mapData.isDrawing = false
        const result = await saveInstitutionsJobsArea(this.mapData)
        console.log(result)
        console.log('提交绘制 => 成功')
        this.$message.success('提交成功')
      } catch (e) {
        console.log('提交绘制 => 失败', e)
      }
    },
    // 取消
    cancel() {
      // 结束编辑
      this.isEditMode = false
    }
  }
}
</script>

<style lang="scss" scoped>
// 自定义图标中隐藏自带箭头
::v-deep .el-tree-node__content>.el-tree-node__expand-icon {
  position: absolute;
  opacity: 0;
}

// 树节点图标
.tree-icon {
  width: 14px;
  height: 14px;
  margin-right: 8px;
}

// 树节点文字
.tree-icon-text {
  font-size: 14px;
  font-weight: 400;
  color: #818693;
}

.institutions-jobs-area-page {
  display: flex;
  flex-direction: row;
  padding: 20px;
  background-color: #f3f5f9;

  .el-select {
    width: 100%;
  }

  .left {
    width: 205px;
    height: 823px;
    margin-right: 20px;

    .card {
      height: 100%;
    }

    .tree {
      height: 100%;
    }
  }

  .right {
    flex: 1;
    height: 100%;

    .search-box {
      span {
        color: #20232a;
        font-weight: 400;
        font-size: 14px;
      }
    }

    .map-container {
      position: relative;
      height: 648px;
      margin-top: 20px;
      // background-color: blue;

      .bm-view {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
      }

      .option-bar {
        position: absolute;
        background-color: #fff;
        padding-bottom: 10px;
        left: 0;
        top: 0;
        width: 100%;
        z-index: 999;

        // 操作栏
        .tip-bar {
          text-align: center;
          background-color: rgb(255, 245, 231);
          margin-top: 10px;

          .tip-icon {
            color: rgb(198, 126, 18);
          }

          .tip {
            font-size: 12px;
            color: rgb(198, 126, 18);
            height: 30px;
            line-height: 30px;
            text-align: left;
            padding-left: 10px;
            margin: 12px 0;
          }
        }
      }
    }
  }
}
</style>
